{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2a901193",
   "metadata": {},
   "source": [
    "## 购物车"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "514c082e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入您的余额3\n",
      "开始购物\n",
      "1 ['韭菜饺', 10]\n",
      "2 ['芹菜饺', 11]\n",
      "3 ['白菜饺', 8]\n",
      "请输入您所需要的商品编号（单选），或者按 r 退出购物r\n",
      "您没有购买任何商品，您的余额为3\n"
     ]
    }
   ],
   "source": [
    "## 输入余额，余额格式错误处理\n",
    "while True:\n",
    "    balance_old = input(\"请输入您的余额\")\n",
    "    if not balance_old.isdigit():   # .isdigit，判断余额是否为数字\n",
    "        print(\"输入格式错误，请重新输入\")\n",
    "    else:\n",
    "        print(\"开始购物\")\n",
    "        balance_old = int(balance_old) # 将输入的字符转为数字\n",
    "        break\n",
    "balance_new = balance_old  # 设定一个新的余额变量，便于在未购买任何商品时打印购买列表\n",
    "balance_new = int(balance_new)\n",
    "\n",
    "    \n",
    "## 顾客选择商品\n",
    "\n",
    "# 商品列表\n",
    "product_list = [\n",
    "[\"韭菜饺\",10],    \n",
    "[\"芹菜饺\",11],\n",
    "[\"白菜饺\",8]    \n",
    "]\n",
    "\n",
    "shopping_list = []\n",
    "\n",
    "\n",
    "while True:\n",
    "    # 生成带序号的商品列表  enumerate,枚举\n",
    "    for index, item in enumerate(product_list):\n",
    "        print(index + 1, item)\n",
    "\n",
    "    enter = input(\"请输入您所需要的商品编号（单选），或者按 r 退出购物\")\n",
    "    if enter.isdigit():\n",
    "        enter = int(enter)\n",
    "\n",
    "        if enter <= len(product_list) and enter > 0:  \n",
    "            print(\"您要购买的是\",product_list[enter - 1][0])  ## 取列表的第一个值，既仅取商品名称\n",
    "            if balance_new >= product_list[enter - 1][1]:\n",
    "                shopping_list.append(product_list[enter - 1][0])\n",
    "                balance_new -= product_list[enter - 1][1]\n",
    "                print(\"您已购买\" + product_list[enter - 1][0] + \",您的余额为\" + str(balance_new))\n",
    "            else:\n",
    "                print (\"您的余额不足，购买失败\")\n",
    "                print(\"您现在的余额为:\" + str(balance_new))\n",
    "\n",
    "\n",
    "        else:\n",
    "            print(\"您所输入的编号为错误编号，请重新输入\")\n",
    "\n",
    "    elif enter == \"r\":\n",
    "        if balance_new == balance_old:\n",
    "            print(\"您没有购买任何商品，您的余额为\" + str(balance_new))\n",
    "        else:\n",
    "            print(\"已退出购物，您的余额为\" + str(balance_new))\n",
    "            print(\"以下是您所购买的商品\" + str(shopping_list))\n",
    "        break    "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
